import {createRouter, createWebHashHistory, VueRouter} from 'vue-router'

import LoginPage from "@/views/LoginPage";
import AsidePage from "@/views/AsidePage";
import ChartOverview from "@/components/ChartOverview";
import SysManager from "@/components/SysManager";
import InventoryView from "@/components/InventoryView"
import RegisterPage from "@/views/RegisterPage"
import * as storage  from '@/util/localstorageutil.js';
import {ElMessage} from "element-plus";

const routes = [

    {
        path: '/login',
        name: 'LoginPage',
        component: LoginPage,
        meta: {requiresAuth: false}
    },
    {
        path: '/register',
        name: 'RegisterPage',
        component: RegisterPage,
        meta: {requiresAuth: false}
    },
    {
        path: '/',
        name: 'AsidePage',
        component: AsidePage,
        redirect: "/sys",  //重定向到第一个子路由
        children: [
            {
                path: 'chart',
                name: 'ChartOverview',
                component: ChartOverview,
                children: [],
                meta: {requiresAuth: true}
            },
            {
                path: 'sys',
                name: 'SysManager',
                component: SysManager,
                children: [],
                meta: {requiresAuth: true}
            }
            ,
            {
                path: 'inventoryview',
                name: 'InventoryView',
                component: InventoryView,
                children: [],
                meta: {requiresAuth: true}
            }
        ],
        meta: {requiresAuth: true}
    },

]

const router = createRouter({
    // history 模式
    // history: createWebHistory(process.env.BASE_URL),

    //hash 模式
    history: createWebHashHistory(process.env.BASE_URL),
    routes
})

function showMessageError(type, message) {
        ElMessage({
            message: message,
            //warning 、error、success
            type: type,
            onClose: () => {
            }
        });
}
    
//全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to, from, next) => {
    console.log('前置路由守卫', to, from)
    if (to.meta.requiresAuth) {
        /*
       从localstorage获取token
        1 如果存在，请求鉴权接口
           1.1 鉴权成功，放行
           1.2 鉴权失败，跳转到登录页面
        2 如果存在，直接跳转到登录页面

    */
        var item = storage.getItem(storage.LS_TOKEN);
        if (item) {
            next();
        } else {
            //给错误提示
            showMessageError("error", "auth valid now redirect login now ")
            storage.clearForLoginOut();
            //如果鉴权不成功
            next('/login');
        }
    } else {
        next();
    }

})

export default router
